import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'

import * as api from '@/apis/index.js'
import { filterParams } from '@/utils/index'

import { loginHost } from '@/config/env'
import { themeList, primaryColorList, layoutList, contentWidthList, defaultUI } from '@/config/ui'

Vue.use(Vuex)

const lastConfig = localStorage.getItem('config')

const state = {
  // 全局设置
  isSettingDrawerShow: false,
  config: lastConfig ? JSON.parse(lastConfig) : defaultUI,
  layoutList,
  themeList,
  primaryColorList,
  contentWidthList,
  isRouterAlive: true,
  breadCrumbs: [],
  tabHistoryList: [],
  // 用户信息
  token: localStorage.getItem('token') || null,
  userInfo: {},
  accountMenuAndPermissions: {},
  // 菜单
  selectedNavKeys: [],
  isSidebarMenuCollapsed: false, // 菜单是否关闭
}

const getters = {
  isSettingDrawerShow: state => state.isSettingDrawerShow,
  config: state => state.config,
  isRouterAlive: state => state.isRouterAlive,
  userInfo: state => state.userInfo,
  token: state => state.token,
  theme: state => {
    const theme = state.themeList.find(item => item.value === state.config.theme)
    return {
      ...theme,
      data: {
        ...theme.data,
        config: state.config,
        'primary-color': state.config.primaryColor,
      }
    }
  },
  themeList: state => state.themeList,
  breadCrumbs: state => state.breadCrumbs,
  tabHistoryList: state => state.tabHistoryList,
  primaryColorList: state => state.primaryColorList,
  isSidebarMenuCollapsed: state => state.isSidebarMenuCollapsed,
  // 获取路由配置数据
  selectedNavKeys: state => state.selectedNavKeys,
  sidebarNavs: state => {
    // return [
    //   {
    //     name: '应用中心',
    //     icon: 'appstore',
    //     children: [
    //       {
    //         name: '应用列表',
    //         url: '/home/app/list',
    //       },
    //     ]
    //   },
    // ]
    const { menu } = state.accountMenuAndPermissions
    function generateMenu (menu = []) {
      return menu.map(item => {
        const obj = {
          name: item.meta.title,
          url: item.url,
          icon: item.meta.icon,
        }
        if (item.url) {
          obj.url = item.url
        }
        if (item.children) {
          obj.children = generateMenu(item.children)
        }
        return obj
      })
    }
    return generateMenu(menu)
  },
  auth: state => {
    const { auth } = state.accountMenuAndPermissions
    const res = {}
    auth && auth.forEach(item => {
      res[item.action] = item
    })
    return res
  },
}

const mutations = {
  setSettingDrawerShow (state, data) {
    state.isSettingDrawerShow = data
  },
  setConfig (state, data) {
    state.config = {
      ...state.config,
      ...data,
    }
    localStorage.setItem('config', JSON.stringify(state.config))
  },
  reload (state, data) {
    state.isRouterAlive = false
    Vue.nextTick(() => {
      state.isRouterAlive = true
    })
  },
  toggleSidebarMenuCollapsed (state) {
    state.isSidebarMenuCollapsed = !state.isSidebarMenuCollapsed
  },
  setSidebarNavs (state, data) { // 重置路由配置数据
    state.sidebarNavs = data
  },
  setToken (state, data) {
    state.token = data
  },
  setUserInfo (state, data) {
    state.userInfo = data
  },
  setSelectedNavKeys (state, data) {
    state.selectedNavKeys = data
  },
  setMenuAndPermissions (state, data) {
    // state.accountMenuAndPermissions = data
  },
  logout (state, flag) {
    state.userInfo = {}
    state.token = null
    window.sessionStorage.removeItem('vuex')
    setTimeout(() => {
      let url = `${loginHost}/#/user/login?from=${location.origin}&grant_type=password`
      if (flag) {
        url += '&logout=true'
      }
      location.href = url
    }, 0)
  },
  setBreadCrumbs (state, data) {
    state.breadCrumbs = data
  },
  // 来自路由守卫
  addTabHistory (state, data) {
    state.tabHistoryList = [
      ...state.tabHistoryList,
      {
        fullPath: data.fullPath,
        path: data.path,
        name: data.name,
        query: data.query,
        params: data.params,
        hash: data.hash,
      }
    ]
  },
  // 来自用户操作tab
  removeTabHistory (state, key) {
    state.tabHistoryList = state.tabHistoryList.filter(item => item.path !== key)
  },
}
const actions = {
  checkToken ({ commit }, params) {
    return api.checkToken(filterParams(params))
      .then(res => {
        return res
      })
      .catch(err => {
        return Promise.reject(err)
      })
  },
  getUserInfo ({ commit }, params) {
    return api.getUserInfo(params)
      .then(res => {
        commit('setUserInfo', res.result)
      })
      .catch(err => {
        return Promise.reject(err)
      })
  },
  getMenuAndPermissions ({ commit }, params) {
    return api.getMenuAndPermissions(params)
      .then(res => {
        commit('setMenuAndPermissions', res.result)
      })
      .catch(err => {
        return Promise.reject(err)
      })
  },
  logout ({ commit }, flag) {
    // api.logout(params)
    commit('logout', flag)
  },
  uploadImg ({ commit }, params) {
    return api.uploadImg(filterParams(params))
  },
}
export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions,
  modules: {
  },
  plugins: [createPersistedState({ storage: window.sessionStorage })],
})
